﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    /// <summary>
    /// 采购订单 OA 操作
    /// </summary>
    [Description("销售报价单审核推送小满"), HotUpdate]
    public class SalQuotationAudit : AbstractOperationServicePlugIn
    {
        public string btype = "销售报价单审核推送小满";
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string logType = "销售报价单审核推送小满";
        public TokenData TokenObj = null;
        public string xmUserUrl = $@"https://api-sandbox.xiaoman.cn/v1/user/list";
        public string url { get; set; } = "https://api-sandbox.xiaoman.cn/v1/invoices/quotation/push";
        Dictionary<string, string> headers = new Dictionary<string, string>() ;
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            try
            {
                List<int> IdList = e.DataEntitys.Select(x => x["Id"].ToStringV1().ToInt32V1()).Distinct().Where(y => y != 0).ToList();
                if (IdList == null|| IdList.Count<1)
                    return;
                var tokens = PostHelper.GetToken(logType);
                if (!tokens.Item1)
                {
                    LogHelper.XiaoManLog($"【获取token错误】【msg:{tokens.Item2.msg}】", logType);
                    return;
                }
                TokenObj = tokens.Item2;
                Main(IdList);
            }
            catch (Exception ex)
            {
                LogHelper.XiaoManLog($"【异常BJD2001】\n【msg:{ex.Message}】", logType);
                return;
            }
        }

        public void Main(List<int> IdList)
        {
            List<SalQuotation> dataList = new List<SalQuotation>();
            //分次查询
            int size = 5000;
            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
                string sql = $@"/*dialect*/ select 
id=main.FID
,xmId=main.FXMID  --小满ID
,date=main.FDATE  --报价日期
,billNo=main.FBILLNO
,name=ISNULL(custL.FNAME,'')+CONVERT(varchar(100),main.FDATE,23)+'报价单'
,custName=custL.FNAME
,custId_xm=cust.F_RLKX_XMCUSTID1 --小满客户ID
,salerName=salerL.FNAME  --销售员
,remarks=main.FNOTE --备注
,bbNumber=bb.FCODE  --币别
,matId_xm=mat.FXMID --物料小满ID
,matNumber=mat.FNUMBER
,matName=matL.FNAME
,qty=enty.FQTY
,taxprice=entyF.FTAXPRICE
--,costAmount=matStock.FREFCOST*enty.FQTY  --成本金额
,costAmount=entyF.FALLAMOUNT --成本金额
,minQty=enty.FSTARTQTY --最小起订量
from T_SAL_QUOTATION main
left join T_SAL_QUOTATIONENTRY enty on main.FID=enty.FID
left join T_SAL_QUOTATIONENTRY_F entyF on enty.FENTRYID=entyF.FENTRYID
left join T_BD_CUSTOMER cust on main.FCUSTID=cust.FCUSTID
left join T_BD_CUSTOMER_L custL on cust.FCUSTID=custL.FCUSTID and custL.FLOCALEID=2052
left join V_BD_SALESMAN saler on main.FSALESMANID=saler.fid
left join V_BD_SALESMAN_L salerL on saler.fid=salerL.fid and salerL.FLOCALEID=2052
left join T_SAL_QUOTATIONFIN mainDetail on main.FID=mainDetail.FID
left join T_BD_CURRENCY bb on mainDetail.FSETTLECURRID=bb.FCURRENCYID
left join T_BD_MATERIAL mat on enty.FMATERIALID=mat.FMATERIALID
left join T_BD_MATERIAL_L matL on mat.FMATERIALID=matL.FMATERIALID and matL.FLOCALEID=2052
left join t_BD_MaterialStock matStock on mat.FMATERIALID=matStock.FMATERIALID
where main.FID in ({string.Join(",", ids)})
and ISNULL(F_RLKX_BJLX,'')='B'
";
                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
                List<SalQuotation> pList = datas.DynamicObjectCollectionToDataList<SalQuotation>();
                dataList.AddRange(pList);
            }
            if (dataList.Count < 1)
                return;

            {
                Dictionary<string, List<SalQuotation>> dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
                headers = new Dictionary<string, string>();
                headers.Add("Authorization", $@"Bearer {TokenObj.token}");
                foreach (var dic in dataDic)
                {
                    List<SalQuotation> valueList = dic.Value;
                    SalQuotation firstData = valueList.FirstOrDefault();
                    bool isAdd = firstData.xmId.IsNullOrEmptyOrWhiteSpace();
                    try
                    {
                        int xmUserId = 0;
                        //获取员工小满Id
                        string resultStr = PostHelper.Get(xmUserUrl, "", headers);
                        JObject ygObj = JsonConvert.DeserializeObject<JObject>(resultStr);
                        if (ygObj["code"].ToStringV1().EqualsV1("200")&& ygObj["message"].ToStringV1().EqualsV1("success"))
                        {
                            JArray ygdatas= JsonConvert.DeserializeObject<JArray>(ygObj["data"].ToStringV1());
                            if (ygdatas!=null&& ygdatas.Count>0)
                            {
                                xmUserId = ygdatas.Where(x => x["full_name"].ToStringV1().EqualsV1(firstData.salerName)).Select(x => x["user_id"].ToStringV1().ToInt32V1()).FirstOrDefault();
                            }
                        }
                        else
                        {
                            LogHelper.XiaoManLog($"【获取小满员工ID失败】【单号：{firstData.billNo} 销售员：{firstData.salerName}】\n【msg:{ygObj["message"].ToStringV1()}】",logType);
                            InitMessage(false, firstData.id.ToStringV1(), firstData.billNo, $"获取小满员工【{firstData.salerName}】ID失败\n错误信息：{ygObj["message"].ToStringV1()}");
                            continue;
                        }
                        if (xmUserId==0)
                        {
                            LogHelper.XiaoManLog($"【查询小满员工id失败】【单号：{firstData.billNo} 销售员：{firstData.salerName}】", logType);
                            continue;
                        }

                        string json = string.Empty;
                        {
                            JObject MainObj = new JObject();
                            if (!isAdd)
                                MainObj["quotation_id"] = firstData.xmId;
                            MainObj["quotation_no"] = firstData.billNo;
                            MainObj["name"] = firstData.name;
                            MainObj["company_id"] = firstData.custId_xm;
                            MainObj["company_name"] = firstData.custName;
                            MainObj["user_id"] = xmUserId;
                            MainObj["remark"] = firstData.remarks;
                            MainObj["currency"] = firstData.bbNumber;
                            //MainObj["currency"] = "CNY";
                            MainObj["quotation_date"] = firstData.date;
                            //MainObj["amount"] = valueList.Sum(x=>x.costAmount);
                            //报价单状态
                            MainObj["status"] = "26054968427772";
                            JArray EntryArray = new JArray();
                            foreach (SalQuotation value in valueList)
                            {
                                JObject EntryObj = new JObject();
                                EntryObj["product_id"] = value.matId_xm;
                                EntryObj["count"] = value.qty;
                                EntryObj["unit_price"] = value.taxprice;
                                EntryObj["cost_amount"] = value.costAmount;
                                EntryObj["minimum_order_quantity"] = value.minQty;
                                EntryArray.Add(EntryObj);
                            }
                            MainObj["product_list"] = EntryArray;
                            json = MainObj.ToStringV1();
                        }
                        string inContent = $"【{firstData.billNo}】【销售报价单】【地址：{url}】\n【header:{JsonConvert.SerializeObject(headers)}】\n【传入内容：{json}】";
                        LogHelper.XiaoManLog(inContent, logType);
                        string reponse = PostHelper.Post(url, json, headers);
                        string outContent = $"【{firstData.billNo}】【销售报价单】【返回内容：{reponse}】";
                        LogHelper.XiaoManLog(outContent, logType);
                        //解析返回数据
                        JObject reObj = JsonConvert.DeserializeObject<JObject>(reponse);
                        if (reObj["code"].ToStringV1().EqualsV1("200") && reObj["message"].ToStringV1().EqualsV1("success"))
                        {
                            //推送销售报价单成功
                            if (isAdd)
                            {
                                JObject dataObj = JsonConvert.DeserializeObject<JObject>(reObj["data"].ToStringV1());
                                string xmid = dataObj["quotation_id"].ToStringV1();
                                DBUtils.Execute(Context, $@"update T_SAL_QUOTATION set FXMID='{xmid}' where FID={firstData.id}");
                            }
                            InitMessage(true, firstData.id.ToStringV1(), firstData.billNo, "推送小满完成");
                        }
                        else
                        {
                            InitMessage(false, firstData.id.ToStringV1(), firstData.billNo, $"推送小满失败\n错误信息：{reponse}");
                        }
                    }
                    catch (Exception ex)
                    {

                        LogHelper.XiaoManLog($"异常【QC1005】【单号：{firstData.billNo} 销售员：{firstData.salerName}】\n【msg:{ex.Message}】", logType);
                        InitMessage(false, firstData.id.ToStringV1(), firstData.billNo, $"推送小满异常【QC1005】\n错误信息：{ex.Message}");
                        continue;
                    }
                }

            }
  


        }

        public void InitMessage(bool status,string id,string no,string msg)
        {
            this.OperationResult.IsShowMessage = true;
            OperateResult operate = new OperateResult()
            {
                SuccessStatus = true,
                PKValue = id,
                Number = no,
                Message = msg,
            };
            this.OperationResult.OperateResult.Add(operate);
        }

    }
}
